# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : config_db_view.py
# Time       ：2023/3/12 13:20
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    流程实例视图
    process instance views
"""
import datetime

from flask_restx import fields
from sqlalchemy import or_

from apis.orderlines import orderlines_ns
from apis.orderlines.models.process import ProcessInstance
from apis.orderlines.schema.process_schema import ProcessInstanceSchema
from public.api_utils.api_decorator import handle_api_error
from public.base_export_excel_view import BaseExportExcelView
from public.base_response import MarshalModel
from public.base_view import BaseView, BaseDetailsView

process_instance = {
    'id': fields.String(description='流程实例ID'),
    'process_instance_id': fields.String(description='流程运行实例ID'),
    'process_name': fields.String(description='流程名称'),
    'version': fields.String(description='流程版本'),
    'version_desc': fields.String(description='版本描述'),
    'process_params': fields.Raw(description='流程运行实例参数'),
    'process_config': fields.Raw(description='流程运行实例流程实例'),
    'start_time': fields.String(description='流程运行实例开始时间'),
    'end_time': fields.String(description='流程运行实例结束时间'),
    'runner': fields.String(description='流程运行实例运行者'),
    'runner_id': fields.Integer(description='流程运行实例运行者ID'),
    'process_error_info': fields.Raw(description='流程错误信息'),
    'process_status': fields.String(description='流程运行实例状态'),
    'mode': fields.String(description='流程运行模式'),
    'namespace': fields.String(description='流程命名空间'),
    'process_id': fields.String(description='流程ID'),
    'run_type': fields.String(description='触发方式'),
}
process_instance_marshal = MarshalModel('process_instance', orderlines_ns)


class ProcessInstanceDetailView(BaseDetailsView):
    url = '/process_instance/detail'

    def __init__(self, *args, **kwargs):
        super(ProcessInstanceDetailView, self).__init__(*args, **kwargs)
        self.table_orm = ProcessInstance
        self.table_schema = ProcessInstanceSchema

    @handle_api_error()
    @orderlines_ns.doc(description="获取流程实例详情")
    @orderlines_ns.expect(process_instance_marshal.detail_request())
    @orderlines_ns.marshal_with(process_instance_marshal.detail_response(process_instance))
    def get(self):
        """获取流程实例详情"""
        return super(ProcessInstanceDetailView, self).get()


class ProcessInstanceView(BaseView):
    url = '/process_instance'

    def __init__(self, *args, **kwargs):
        super(ProcessInstanceView, self).__init__(*args, **kwargs)
        self.table_orm = ProcessInstance
        self.table_schema = ProcessInstanceSchema

    def handle_filter(self):
        self.filter.append(self.table_orm.active == 1)
        for key, val in self.form_data.items():
            if hasattr(self.table_orm, key) and val:
                self.filter.append(getattr(self.table_orm, key) == val)
            if key == 'keyword' and val:
                self.filter.append(or_(
                    self.table_orm.id == val,
                    self.table_orm.process_id == val,
                    self.table_orm.process_instance_id == val
                ))

    @handle_api_error()
    @orderlines_ns.doc(description='获取流程实例详情')
    @orderlines_ns.expect(process_instance_marshal.list_request(process_instance))
    @orderlines_ns.marshal_with(process_instance_marshal.list_response(process_instance))
    def get(self):
        """获取流程实例详情"""
        return super(ProcessInstanceView, self).get()

    @handle_api_error()
    @orderlines_ns.doc(description='创建流程实例')
    @orderlines_ns.expect(process_instance_marshal.create_request(process_instance))
    @orderlines_ns.marshal_with(process_instance_marshal.create_response())
    def post(self):
        """创建流程实例"""
        return super(ProcessInstanceView, self).post()

    @handle_api_error()
    @orderlines_ns.doc(description='修改流程实例')
    @orderlines_ns.expect(process_instance_marshal.update_request(process_instance))
    @orderlines_ns.marshal_with(process_instance_marshal.update_response())
    def put(self):
        """修改流程实例"""
        return super(ProcessInstanceView, self).put()

    @handle_api_error()
    @orderlines_ns.doc(description='删除流程实例')
    @orderlines_ns.expect(process_instance_marshal.delete_request())
    @orderlines_ns.marshal_with(process_instance_marshal.delete_response())
    def delete(self):
        """删除流程实例"""
        return super(ProcessInstanceView, self).delete()


class ProcessInstanceReportView(BaseExportExcelView):
    """普通流程导出, common process export"""
    url = '/process_instance/export'

    def __init__(self, *args, **kwargs):
        super(ProcessInstanceReportView, self).__init__(*args, **kwargs)
        self.file_name = f'process_instance_{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}'
        self.columns = {
            'process_id': '流程id',
            'process_name': '流程名称',
            'process_params': '流程参数',
            'process_config': '流程流程实例',
            'start_time': '开始时间',
            'end_time': '结束时间',
            'runner': '运行者',
            'runner_id': '运行者id',
            'process_error_info': '流程异常信息',
            'process_status': '流程状态',
        }

    @handle_api_error()
    @orderlines_ns.doc(description='导出流程实例')
    @orderlines_ns.expect(process_instance_marshal.list_request(process_instance))
    def post(self):
        """导出流程实例"""
        return super(ProcessInstanceReportView, self).post()
